<template>
  <view class="report-container">
    <e-navbar leftTitle="测算报告"></e-navbar>
    <scroll-view scroll-y class="report-body" :style="{'height': scrollHeight + 'px'}">
      <image class="report-bg" :src="$image('/images/report-bg.png')" mode="aspectFill"></image>
      <view class="report-body_content">
        <view class="report-header">
          <view class="report-header_left"></view>
          <view>生辰综合详情</view>
          <view class="report-header_right"></view>
        </view>
        <!--<view class="grid-container">-->
        <!--  <u-parse :content="zwGong" :tagStyle="zwGongStyle"></u-parse>-->
        <!--</view>-->

        <view class="grid-container">
          <view class="grid-item" v-for="(item, index) in zwGongPan" :key="index" :class="{'large': index === 5}">
            <template v-if="index !== 5">
              <view class="left-top">
                <view class="left-top_title" v-for="(item,index) in item.Star6" :key="index">{{ item.slice(0,2) }}</view>
                <view class="min-text">
                  <view class="" v-for="(mitem, mindex) in gridStars(item)" :key="mindex">{{mitem.slice(0,2)}}</view>
                </view>
              </view>
              <view class="left-bottom">{{item.MangB}}</view>
              <view class="right-bottom" v-html="item.MangA"></view>
              <!--<view class="right-top" v-if="index == 2 || index == 10 || index == 12">-->
              <!--  <image :src="$image('/images/report-tag.png')" mode="aspectFill"></image>-->
              <!--  <view class="tag-text">{{item.right_top_tag}}</view>-->
              <!--</view>-->
            </template>
            <template v-else>
              <view class="grid-center-container">
                <view>
                  <text class="title-color">姓名:</text>
                  <text>{{ userData.nickname }}</text>
                </view>
                <view>
                  <view class="title-color">阳历:</view>
                  <view>{{zwGongData.solarday}}</view>
                </view>
                <view>
                  <view class="title-color">阴历:</view>
                  <view>{{zwGongData.lunarday}}</view>
                </view>
                <view>
                  <text class="m-r-10">{{ zwGongData.yinyanggender }}</text>
                  <text>{{ zwGongData.fiveelement }}</text>
                </view>
                <view class="flex col-center">
                  <text class="title-color">生肖:</text>
                  <text class="m-r-10">{{ zwGongData.shenxiao }}</text>
                  <text class="m-r-10">{{ zwGongData.age }}虚岁</text>
                  <text>子斗在{{ zwGongData.doujun.zd }}</text>
                </view>
                <view>
                  <text class="title-color">命主:</text>
                  <text class="m-r-10">{{ zwGongData.mingzhu }}</text>
                  <text class="title-color">身主:</text>
                  <text>{{ zwGongData.shenzhu }}</text>
                </view>
                <!--<view>本命佛：大日如来</view>-->
              </view>
            </template>
          </view>
        </view>
        <u-gap height="40"></u-gap>
        <view class="font-24 text-center">
          <text>命盘显示，2024年你的感情、事业、财运会出现</text>
          <text style="color: #FFC735">重要变动</text>
        </view>
        <u-gap height="20"></u-gap>
<!--        <view class="report-btn">-->
<!--          <image :src="$image('/images/report-btn.png')" mode="scaleToFill" @click="handleGetBirthInfo()"></image>-->
<!--        </view>-->
        <view class="result-body" v-if="aiResultStr" style="white-space: pre-line;" v-html="aiResultStr"></view>
        <u-gap height="30"></u-gap>
      </view>
    </scroll-view>
    <!-- 支付方式弹窗 -->
    <e-pay-type-popup ref="payTypeRef" @choose="handleChoosePayType"></e-pay-type-popup>
    <!--  确认支付弹窗  -->
    <e-pay-popup ref="payPopupRef" @paySuccess="handlePayResult"></e-pay-popup>

  </view>
</template>

<script>
let app = getApp();
import {getAiZangGan, getCalendarDate} from "@/common/utils";
import {agent_chat} from "@/common/mock";
import {wxPay} from "@/common/pay";

export default {
  data() {
    return {
      scrollHeight: 0,
      userData: {},
      zwGong: "",
      zwGongStyle:{
        table: "border: 1px solid red;width: 710rpx;",
        tr: "border: 1px solid red;"
      },
      // 流年运势请求参数
      zwPanQuery:{
        year: "",
        month: "",
        day: "",
        hour: "",
        genderValue: "",
      },
      zwGongPan: [], //按道理13个数组,  下标第五个为空
      zwGongData: [], //所有数据,  包含中间的
      agent_chat: JSON.parse(JSON.stringify(agent_chat)),
      userinfo: {},
      augurDate: {},
      aiResultStr: "", //ai回答

    };
  },
  onLoad(options) {
    if(options.userData){
      this.userData = JSON.parse(decodeURIComponent(options.userData));
      this.zwPanQuery.genderValue = this.userData.gender == "女" ? "F" : "M";
      this.getGongPan(this.userData.birthday);
      this.getUserInfo(options.order_id, options.userData);

    }
  },
  onReady() {
    this.getElInfo();
  },
  computed: {
    gridStars() {
      return function (item){
        const star6Length = item.Star6.length;
        let arr = [];
        // 根据 Star6 的长度返回相应的切片
        if (star6Length >= 2) {
          arr = item.allStar.slice(0, 1);
        } else if (star6Length === 1) {
          arr = item.allStar.slice(0, 2);
        } else {
          arr = item.allStar.slice(0, 4);
        }
        return arr;
      }
    }
  },
  methods: {
    // 获取紫薇十二宫数据
    async getGongPan(birthday){
      let date = await getCalendarDate({
        date:this.$u.timeFormat(birthday, 'yyyy-mm-dd hh:MM:ss')
      });
      this.zwPanQuery.year = date.solarYear * 1;
      this.zwPanQuery.month = date.solarMonth * 1;
      this.zwPanQuery.day = date.solarDay * 1;
      this.zwPanQuery.hour = date.lunarHour.slice(0,1);
      const res = await this.$api.zwpan(this.zwPanQuery);
      if(res.code == 1){
        let data = res.data;
        // 紫薇盘重置排序
        let zwGongSort = [5,6,7,8,4,9,3,10,2,1,0,11];
        // 构建并排序数据
        const list = zwGongSort.map((item) => {
          const currentZw = data.zw[item];
          return {
            ...currentZw,
            allStar: [
              ...currentZw.StarA,
              ...currentZw.StarB,
              ...currentZw.StarC,
              ...currentZw.StarD,
              ...currentZw.StarE,
              ...currentZw.StarF,
              ...currentZw.StarJ,
              ...currentZw.StarS,
            ],
          };
        });
        list.splice(5 , 0, []);
        this.zwGongPan = list;
        this.zwGongData = data;
        console.log("tttttttt", JSON.stringify(list));
      }
    },
    async getElInfo() {
      let systemInfo = this.$u.sys();
      let rectInfo = await this.$u.getRect('.report-header');
      this.scrollHeight = systemInfo.windowHeight - rectInfo.top;
      console.log(this.scrollHeight);
    },
    async handleGetBirthInfo(){
      this.$refs.payTypeRef.handleShowPayTypePopup({});
      // // 跳转之前调起支付
      // const res = await this.$api.create_payment({
      //   description: "liunian"
      // });
      // if(res.code == 1){
      //   wxPay(res.data, result=>{
      //     console.log("查看回调", result);
      //     if(result.code == 1){
      //       uni.navigateTo({
      //         url: "/pagesAugur/result/result"
      //       })
      //     }
      //   })
      // }
    },
    // 组件中选择支付方式
    handleChoosePayType(val){
      console.log("组件中选择支付方式", val);
      let data = {
        payType: val,
        payWay: "liunian"
      }
      this.$refs.payPopupRef.handleShowPayPopup({}, data);
    },
    // 支付结果
    handlePayResult(data){
      console.log("支付回调", data);
      let url = "/pagesAugur/result/result";
      if(data && data.order_id){
        url = url + "?order_id=" + data.order_id;
      }
      uni.navigateTo({
        url
      })
    },
    async getUserInfo(order_id = null, userData = null){
      app.getMineInfo().then(async (res)=>{
        this.userinfo = res;
        app.isCompleteInfo();
        if(this.userinfo){
          let agent_type = 6;//6=流年运势, 7=详批八字
          if(userData){
            let birthdayData = JSON.parse(decodeURIComponent(userData));
            this.userinfo.birthday = birthdayData.birthday;
            this.userinfo.gender = birthdayData.gender;
            this.userinfo.nickname = birthdayData.nickname;
            agent_type = birthdayData.agent_type;
          }
          this.augurDate = await getCalendarDate({
            date:this.$u.timeFormat(this.userinfo.birthday, 'yyyy-mm-dd hh:MM:ss'),
            shenShaParams: {
              // isShenSha: true,
              day: this.$u.timeFormat(this.userinfo.birthday, "yyyy-mm-dd hh:MM:ss"),
              sex: this.userinfo.gender === "男" ? 1 : 0,
              name: this.userinfo.nickname,
            }
          });
          let {
            lunarDateChinese,
            shiShen,
            zangGan,
            naYin,
            kongWang,
            daYun,
            liuNian,
            jiShenXiongSha,
            aiZangGan
          } = this.augurDate;
          let bazi = {
            profile: {
              "姓名": this.userinfo.nickname,
              "性别": this.userinfo.gender,
            },
            "公历": this.$u.timeFormat(this.userinfo.birthday, "yyyy-mm-dd hh:MM:ss"),
            "农历": lunarDateChinese,
            "十神": shiShen,
            "纳音": naYin,
            "空亡": kongWang,
            "大运": daYun,
            "流年": liuNian.allData,
            "吉神凶煞": jiShenXiongSha,
            "藏干": aiZangGan,
          };
          let newBazi = Object.assign(this.agent_chat.bazi, bazi);
          this.agent_chat.birthday = this.$u.timeFormat(this.userinfo.birthday, 'yyyy-mm-dd');
          this.agent_chat.bazi = JSON.stringify(newBazi);
          if(this.augurDate.zangGan && this.augurDate.zangGan.length > 0){
            getAiZangGan(this.augurDate.zangGan);
            let data = {
              agent_type: Number(agent_type),
              query: agent_type == 6 ?"流年运势" : "详批八字",
              // isAi: true,
            };
            if(order_id){
              data.order_id = order_id;
            }
            this.agent_chat.request_time = this.$u.timeFormat(new Date().getTime(), "yyyy-mm-dd hh:MM:ss");
            const result = await this.$api.req_chat({...this.agent_chat, ...data});
            // if(result.result !== "" && result.status == "SUCCESS"){
            if(result.code == 1){
              console.log("查看流年运势回调", result);
              // 使用解析函数
              // this.newData = this.parseTextToObject(result.result);
              this.aiResultStr = result.data.result;
              console.log(this.aiResultStr);
            }
          }
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
  .report-container{
    color: #fff;
    .report-body{
      position: relative;
      .report-bg{
        height:100%;
        width: 100%;
        display: block;
        position: fixed;
        left: 0;
        top: 0;
      }
      &_content{
        position: relative;
        z-index: 1;
        .report-header{
          padding: 30rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 37rpx;
          font-family: 'pingfang-heavy';
          background: rgba(35,83,155,0.5);
          &_left,&_right{
            flex: 1;
            height: 4rpx;
          }
          &_left{
            background: linear-gradient(270deg, #A9B8EF 0%, rgba(169,184,239,0) 100%);
            border-radius: 2rpx;
            margin-right: 30rpx;
          }
          &_right{
            background: linear-gradient(90deg, #A9B8EF 0%, rgba(169,184,239,0) 100%);
            border-radius: 2rpx;
            margin-left: 30rpx;
          }
        }
        .grid-container {
          display: grid;
          grid-template-columns: repeat(4, 1fr); /* 4列 */
          grid-template-rows: repeat(4, 1fr); /* 4行 */
          gap: 10rpx; /* 网格之间的间距 */
          width: 95vw;
          height: 95vw; /* 保持网格是正方形 */
          margin: 50rpx auto 0 auto; /* 居中 */

          /deep/ table{
            box-sizing: border-box;
             border: 1px solid yellow !important;
            width: 710rpx !important;
            display: grid;
            gap: 10rpx;
            table,tbody,tr{
              width: 100%;
            }
            td{
              width: calc(100% / 4);
            }
            table,tbody,tr,td{
              box-sizing: border-box;
            }
            tbody{
              tr:first-child{
                // display: flex;
                // gap: 10rpx;
                // border: 1px solid blue;
                td:nth-child(2),td:nth-child(3){
                }
              }
            }
          }
        }

        .grid-item {
          background: linear-gradient(-45deg, rgba(48, 84, 202, 0.5) 0%, rgba(60, 160, 206, 0.5) 100%);
          color: white;
          border: 1px solid #ECC464;
          box-sizing: border-box;
          border-radius: 10rpx;
          position: relative;
          .left-top{
            font-size: 28rpx;
            color: #B7D1FF;
            margin-top: 8rpx;
            margin-left: 12rpx;
            &_title{
              line-height: 36rpx;
            }
            .min-text{
              color: #F48A86;
              font-size: 20rpx;
            }
          }
          .left-bottom{
            background: #ECC464;
            border-top-right-radius: 20rpx;
            padding: 4rpx 20rpx;
            color: #3D3201;
            font-size: 26rpx;
            display: inline-block;
            position: absolute;
            left: 0;
            bottom: 0;
            font-family: 'pingfang-heavy';
          }
          .right-bottom{
            width: 30rpx;
            color: #FFC735;
            font-size: 26rpx;
            position: absolute;
            right: 2rpx;
            bottom: 2rpx;
          }
          .right-top{
            position: absolute;
            right: -8rpx;
            top: -8rpx;
            font-size: 20rpx;

            image{
              width: 70rpx;
              height: 70rpx;
              display: block;
            }
            .tag-text{
              position: absolute;
              top: 50%;
              left: 50%;
              width: 100%;
              text-align: center;
              font-family: 'pingfang-heavy';
              transform: translate(-50%, -50%);
            }
          }
          .grid-center-container{
            height: 100%;
            font-size: 26rpx;
            padding: 20rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .title-color{
              color: #ECC464;
            }
          }
        }

        .large {
          grid-column: 2 / 4; /* 从第2列跨到第4列 */
          grid-row: 2 / 4; /* 从第2行跨到第4行 */
        }
        .report-btn{
          padding: 0 20rpx;
          image{
            height: 108rpx;
            width: 100%;
            display: block;
          }
        }
      }
    }
    .result-body {
      border-radius: 20rpx;
      overflow: hidden;
      font-size: 26rpx;
      background: #F5F5F5;
      margin: 20rpx;
      padding: 20rpx;
      color: #333;
    }
  }
</style>
